package com.gillion.grule.client.components;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gillion.grule.client.core.Component;
import com.gillion.grule.client.core.Context;
import com.gillion.grule.client.core.ExecuteComponent;
import com.gillion.grule.client.core.GroovyShellConfig;
import com.gillion.grule.client.utils.GroovyUtils;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;








@Component("GroovyShellService")
public class GroovyShellComponent
        extends ExecuteComponent
{
    private static final Logger LOGGER = LoggerFactory.getLogger(GroovyShellComponent.class);


    public <T> T execute(String express, Context context) {
        LOGGER.info("规则引擎 调用 GroovyShell 配置：" + express);
        JSONObject jSONObject = JSON.parseObject(express);
        String shellName = jSONObject.get("shellName").toString();
        List params = (List)jSONObject.get("params");



        Optional<GroovyShellConfig> groovyShellConfigOptional = context.getGroovyShellConfigs().stream().filter(groovyShellConfig -> groovyShellConfig.getShellName().equals(shellName)).findFirst();

        GroovyShellConfig shellConfig = groovyShellConfigOptional.orElseThrow(() -> new RuntimeException("未找到shellName为" + shellName + "的groovy脚本组件"));
        Object result = GroovyUtils.invokeWithCache(shellConfig.getScriptText(), shellConfig.getFunctionName(), params.toArray());
        return (T)result;
    }
}